// MongoDB图库管理模型
import { getMongoDB } from '../config/multi-database.js';

class GalleryMongo {
  constructor(data) {
    this._id = data._id;
    this.name = data.name;
    this.description = data.description || '';
    this.imageUrl = data.imageUrl;
    this.thumbnailUrl = data.thumbnailUrl;
    this.fileSize = data.fileSize || 0;
    this.fileType = data.fileType || '';
    this.dimensions = data.dimensions || '';
    this.category = data.category || 'other';
    this.usageType = data.usageType || 'general';
    this.tags = data.tags || [];
    this.isActive = data.isActive !== undefined ? data.isActive : true;
    this.sortOrder = data.sortOrder || 0;
    this.createdBy = data.createdBy;
    this.createdAt = data.createdAt || new Date();
    this.updatedAt = data.updatedAt || new Date();
  }

  // 获取图库列表
  static async findAll({ page = 1, limit = 20, category, usageType, isActive, search } = {}) {
    try {
      const db = getMongoDB();
      const skip = (page - 1) * limit;
      
      // 构建查询条件
      const query = {};
      
      if (category) query.category = category;
      if (usageType) query.usageType = usageType;
      if (isActive !== undefined) query.isActive = isActive;
      
      if (search) {
        query.$text = { $search: search };
      }
      
      // 获取总数
      const total = await db.collection('gallery').countDocuments(query);
      
      // 获取数据
      const cursor = db.collection('gallery')
        .find(query)
        .sort({ sortOrder: 1, createdAt: -1 })
        .skip(skip)
        .limit(limit);
      
      const data = await cursor.toArray();
      
      return {
        data: data.map(item => new GalleryMongo(item)),
        pagination: {
          page,
          limit,
          total,
          totalPages: Math.ceil(total / limit)
        }
      };
    } catch (error) {
      console.error('MongoDB获取图库列表失败:', error);
      throw error;
    }
  }

  // 根据ID查找图片
  static async findById(id) {
    try {
      const db = getMongoDB();
      const objectId = new ObjectId(id);
      const data = await db.collection('gallery').findOne({ _id: objectId });
      
      return data ? new GalleryMongo(data) : null;
    } catch (error) {
      console.error('MongoDB获取图片详情失败:', error);
      throw error;
    }
  }

  // 创建图片
  static async create(galleryData) {
    try {
      const db = getMongoDB();
      
      const data = {
        ...galleryData,
        createdAt: new Date(),
        updatedAt: new Date()
      };
      
      const result = await db.collection('gallery').insertOne(data);
      
      return new GalleryMongo({ ...data, _id: result.insertedId });
    } catch (error) {
      console.error('MongoDB创建图片失败:', error);
      throw error;
    }
  }

  // 更新图片
  static async update(id, updateData) {
    try {
      const db = getMongoDB();
      const objectId = new ObjectId(id);
      
      const update = {
        $set: {
          ...updateData,
          updatedAt: new Date()
        }
      };
      
      const result = await db.collection('gallery').findOneAndUpdate(
        { _id: objectId },
        update,
        { returnDocument: 'after' }
      );
      
      return result ? new GalleryMongo(result) : null;
    } catch (error) {
      console.error('MongoDB更新图片失败:', error);
      throw error;
    }
  }

  // 删除图片
  static async delete(id) {
    try {
      const db = getMongoDB();
      const objectId = new ObjectId(id);
      
      const result = await db.collection('gallery').deleteOne({ _id: objectId });
      
      return result.deletedCount > 0;
    } catch (error) {
      console.error('MongoDB删除图片失败:', error);
      throw error;
    }
  }

  // 根据用途类型查找图片
  static async findByUsageType(usageType, limit = 10) {
    try {
      const db = getMongoDB();
      
      const cursor = db.collection('gallery')
        .find({ 
          usageType,
          isActive: true 
        })
        .sort({ sortOrder: 1, createdAt: -1 })
        .limit(limit);
      
      const data = await cursor.toArray();
      
      return data.map(item => new GalleryMongo(item));
    } catch (error) {
      console.error('MongoDB按用途查找图片失败:', error);
      throw error;
    }
  }

  // 获取分类统计
  static async getCategoryStats() {
    try {
      const db = getMongoDB();
      
      const pipeline = [
        {
          $group: {
            _id: '$category',
            count: { $sum: 1 },
            active_count: {
              $sum: { $cond: [{ $eq: ['$isActive', true] }, 1, 0] }
            }
          }
        },
        {
          $project: {
            category: '$_id',
            count: 1,
            active_count: 1,
            _id: 0
          }
        },
        { $sort: { count: -1 } }
      ];
      
      const result = await db.collection('gallery').aggregate(pipeline).toArray();
      
      return result;
    } catch (error) {
      console.error('MongoDB获取分类统计失败:', error);
      throw error;
    }
  }

  // 获取使用统计
  static async getUsageStats() {
    try {
      const db = getMongoDB();
      
      const pipeline = [
        {
          $group: {
            _id: '$usageType',
            count: { $sum: 1 },
            active_count: {
              $sum: { $cond: [{ $eq: ['$isActive', true] }, 1, 0] }
            }
          }
        },
        {
          $project: {
            usage_type: '$_id',
            count: 1,
            active_count: 1,
            _id: 0
          }
        },
        { $sort: { count: -1 } }
      ];
      
      const result = await db.collection('gallery').aggregate(pipeline).toArray();
      
      return result;
    } catch (error) {
      console.error('MongoDB获取使用统计失败:', error);
      throw error;
    }
  }

  // 批量更新排序
  static async updateSortOrder(sortData) {
    try {
      const db = getMongoDB();
      const session = db.client.startSession();
      
      try {
        session.startTransaction();
        
        for (const item of sortData) {
          const objectId = new ObjectId(item.id);
          await db.collection('gallery').updateOne(
            { _id: objectId },
            { $set: { sortOrder: item.sortOrder, updatedAt: new Date() } },
            { session }
          );
        }
        
        await session.commitTransaction();
        return true;
      } catch (error) {
        await session.abortTransaction();
        throw error;
      } finally {
        await session.endSession();
      }
    } catch (error) {
      console.error('MongoDB批量更新排序失败:', error);
      throw error;
    }
  }

  // 搜索图片
  static async searchImages(query, page = 1, limit = 20) {
    try {
      const db = getMongoDB();
      const skip = (page - 1) * limit;
      
      const searchQuery = {
        $text: { $search: query }
      };
      
      // 获取总数
      const total = await db.collection('gallery').countDocuments(searchQuery);
      
      // 获取数据
      const cursor = db.collection('gallery')
        .find(searchQuery)
        .sort({ score: { $meta: 'textScore' } })
        .skip(skip)
        .limit(limit);
      
      const data = await cursor.toArray();
      
      return {
        data: data.map(item => new GalleryMongo(item)),
        pagination: {
          page,
          limit,
          total,
          totalPages: Math.ceil(total / limit)
        }
      };
    } catch (error) {
      console.error('MongoDB搜索图片失败:', error);
      throw error;
    }
  }
}

// 导入ObjectId
import { ObjectId } from 'mongodb';

export default GalleryMongo;